import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		token: '',
		uerInfo: {},
		roles: [],
		projectInfo: {},
		hasLogin: false
	},
	mutations: {
		SET_TOKEN: (state, token) => {
		  state.token = token
		},
		SET_USERINFO: (state, uerInfo) => {
		  state.uerInfo = uerInfo
		},
		SET_ROLES: (state, roles) => {
		  state.roles = roles
		},
		SET_HASLOGIN: (state, hasLogin) => {
		  state.hasLogin = hasLogin
		},
		SET_PROJECTINFO: (state, projectInfo) => {
		  state.projectInfo = projectInfo
		}
	},
	actions: {
		// 登录-获取token
		Login({ commit }, token) {
			commit('SET_HASLOGIN', true)
			commit('SET_TOKEN', token)
			uni.setStorageSync('token', token)
		},
		// 登录-储存userInfo
		GetUserInfo({ commit }, res) {
			return new Promise((resolve, reject) => {
				commit('SET_USERINFO', res.user)
				uni.setStorageSync('userInfo', res.user)
				commit('SET_ROLES', res.roles)
				uni.setStorageSync('roles', res.roles)
			  resolve(uni.getStorageSync('userInfo'))
			})
		},
		// 登录-储存roles
		GetRoles({ commit }, roles) {
			commit('SET_ROLES', roles)
			uni.setStorageSync('roles', roles)
		},
		// 登出-清除缓存
		Logout({ commit, state }) {
			commit('SET_TOKEN', '')
			commit('SET_USERINFO', {})
			commit('SET_ROLES', [])
			commit('SET_HASLOGIN', false)
			uni.removeStorageSync('token')
			uni.removeStorageSync('userInfo')
			uni.removeStorageSync('roles')
		},
		SetProjectInfo({ commit }, projectInfo) {
			commit('SET_PROJECTINFO', projectInfo)
			uni.setStorageSync('projectInfo', projectInfo)
		}
	}
})

export default store
